package openase.dsp.conversion;

import openase.dsp.FrequencyDomain;
import openase.dsp.TimeDomain;

import org.apache.commons.math.complex.Complex;
import org.apache.commons.math.transform.FastFourierTransformer;


public class DefaultTimeDomainToFrequencyDomainConverterImpl implements TimeDomainToFrequencyDomainConverter {

    @Override
    public FrequencyDomain[] convert(TimeDomain timeDomain, int chunkSize) {
        byte[] tdValues = timeDomain.values();
        int tdSize = tdValues.length;
        
        final int fdSize = tdSize / chunkSize;
        //final int residual = tdSize % chunkSize;// the rest of the time domain. will not be used

        FrequencyDomain[] fds = new FrequencyDomain[fdSize];
        
        // translate bytes to complex numbers to deal with the frequency domain

        FastFourierTransformer fft = new FastFourierTransformer();
        
        for (int fdIndex = 0; fdIndex < fdSize; fdIndex++) {
            // creates a Complex[] with 'chunkSize' complex numbers
            Complex[] complex = new Complex[chunkSize];
            // the complex numbers created are 'chunkSize' sequential values in the time domain
            int offset = (fdIndex * chunkSize);
            for (int i = 0; i < chunkSize; i++) {
                // Put the time domain data into a complex number with imaginary part as 0:
                complex[i] = new Complex(tdValues[offset + i], 0);

            }
            // Perform the FFT on the chunk
            Complex[] transformed = fft.transform(complex);
            fds[fdIndex] = new FrequencyDomain(transformed);
        }
        
        return fds;
    }

}
